import React, { useEffect, useRef, useState } from 'react';
import { ProFormUploadButton } from '@ant-design/pro-components';
import { fileUploadFun } from '@/services/ant-design-pro/systemApi';

const MyFileUpload = (props) => {
  const { onChange, label = '', rules = [], max = 1 } = props;
  let [fileList, setFileList] = useState([]);
  let uploadRef = useRef();

  // 上传之前校验
  const onBeforeUpload = () => {
    return true;
  };

  // 自定义上传方法
  const customUpload = async ({ file }) => {
    let res = await fileUploadFun(file);
    setFileList((prevList) => [
      ...prevList,
      {
        ...file,
        url: res.data.url,
      },
    ]);
  };

  // 文件删除触发
  const onRemove = (file) => {
    setFileList((prevList) => prevList.filter((item) => item.uid !== file.uid));
  };

  // 图片更新触发
  useEffect(() => {
    onChange(fileList);
  }, [fileList]);

  useEffect(() => {
    if (props.value) {
      const list = props.value.split(',').map((item) => ({
        uid: item,
        name: item,
        status: 'done',
        url: item,
      }));
      setFileList(list);
    }
  }, [props.value]);

  return (
    <>
      <ProFormUploadButton
        fieldRef={uploadRef}
        accept="image/*"
        name={props.name}
        label={label}
        max={max}
        fieldProps={{
          name: 'file',
          listType: 'picture-card', // 上传列表的内建样式，支持四种基本样式 text, picture, picture-card 和 picture-circle
          customRequest: customUpload,
          beforeUpload: onBeforeUpload,
          onRemove: onRemove,
        }}
        fileList={fileList}
        rules={rules}
      />
    </>
  );
};

export default MyFileUpload;
